<?php

namespace app\devices\controller;

use app\devices\service\SocketService;
use think\admin\Controller;
use think\admin\extend\CodeExtend;
use think\admin\service\AdminService;
use think\cache\driver\Redis;

/**
 * 箱格管理
 * Class Boxs
 * @package app\data\controller
 */
class Boxs extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'JcgBoxs';

    protected $box_types = [1=>'大柜', 2=>'中柜', 3=>'小柜'];
    protected $box_status = [1=>'正常', 2=>'使用', 3=>'异常',4=>'停用',5=>'损坏'];
    protected $locks = [1=>'已锁', 0=>'未锁', 2=>'未知'];

    /**
     * 箱格管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index(){
        $map = $d_map = [];
        $user = $this->app->session->get("user");
        $stores = str2arr($user['stores'] ?? '');
        if($user['id']!=10000){
            if($stores) {
                $d_ids = $this->app->db->name("jcg_devices")->where('store_id', "in", $stores)->column("id");
                if($d_ids) {
                    $d_map[] = ['id', "in", $d_ids];
                    $map[] = ['d_id', "in", $d_ids];
                }
            }
        }
        $this->user_stores = $stores;


        $this->devices = $this->app->db->name("jcg_devices")->where($d_map)->column("device_name", 'id');
        $this->title = '箱格管理';
        $query = $this->_query($this->table);
        $query->equal("d_id,box_status,device_board,box_num,is_lock")->like('name,address');

        $query->setOption('order', ['d_id'=>'ASC', 'device_board'=>'ASC', 'box_num'=>'ASC']);
        $query->where($map)->order('d_id ASC, box_num ASC')->equal('status')->dateBetween('create_at')->page();
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _page_filter(array &$data)
    {
        if($data){
            $ids = array_column($data, 'user_id');
            $users = $this->app->db->name("data_user")->where("id", "in", $ids)->column("phone, nickname", 'id');
            foreach ($data as &$row){
                $row['device_name'] = $this->devices[$row['d_id']]??'';
                $row['is_lock'] = $this->locks[$row['is_lock']]??'未知';
                $row['user_id'] = $row['user_id']?"ID：".$row['user_id'].'；手机号：'.($users[$row['user_id']]['phone']??''):"";
            }
        }
    }

    public function clears(){
        $id = input("id");

        if($id){
            if($this->app->db->name("jcg_devices_order")->where(["box_id"=>$id, 'status'=>1])->value("id")){
                $this->error("当前箱子有订单正在使用中，清除失败");
            }

            $res = $this->app->db->name($this->table)->where("id", $id)->update(["user_id"=>0, "box_status"=>1]);
            if($res){
                $this->success("清除成功");
            }else{
                $this->error("清除失败");
            }
        }else{
            $this->error("设备不存在");
        }
    }

    public function unlock(){
        $ch = input("ch");
        $d_id = input("id");
        $device_board = input("device_board");
        $order_id = input("order_id",0);
        $box_id = input("box_id",0);

        $device_id = $this->app->db->name("jcg_devices")->where('id', $d_id)->value('device_id');
        if($device_id){
            try{
                $socket = new SocketService($this->app);
                $msg = ['type'=>2, 'device_id'=>$device_id, 'ch'=>$ch, 'device_board'=>$device_board];
                $socket->sendSocket($msg);
            }catch (\Exception $e){
                $this->error("指令发送失败：".$e->getMessage());
            }

            jcgoplog('开锁','后台用户开锁', AdminService::instance()->getUserName(),0,$order_id, $box_id);

            $this->success("已发送开锁指令");
        }else{
            $this->error("设备不存在");
        }
    }

    /**
     * 添加箱格
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        $this->title = '添加箱格';
        $this->_form($this->table, 'form');
    }

    /**
     * 编辑箱格
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $this->title = '编辑箱格';
        $this->assign("devices", $this->app->db->name('jcg_devices')->column("device_name", "id"));
        $this->_form($this->table, 'edit');
    }

    /**
     * 查看箱格
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function see()
    {
        $this->title = '查看箱格';
        $this->_form($this->table, 'form');
    }

    /**
     * 数据表单处理
     * @param array $data
     * @return array
     */
    protected function _form_filter(array &$data)
    {
        if($this->app->request->isPost()){
            if($this->app->request->action()=='edit'){
                $redis = new Redis();
                $redis->handler()->lrem("BoxIds:".$data['d_id'], $data['id'],0);
                return $data;
            }
            $user = $this->app->session->get("user");
            $data['s_id'] = $user['id'];

            $query = $this->app->db;
            $query->startTrans();
            try{
                $device = $query->name("jcg_devices")->find($data['d_id']);
                if(empty($device)){
                    $this->error("设备不存在");
                }

                $fields = "max(box_num) as box_num_max";

                $boards = $query->name("jcg_boxs")->where("d_id",$data['d_id'])->group("device_board")->column('device_board');

                foreach ($boards as $key=>$board){
                    $fields .= ", max(if(device_board='".$board."',board_channel,0)) as board_".$board.'_max';
                }

                $maxs = $query->name("jcg_boxs")->fieldRaw($fields)->where("d_id",$data['d_id'])->find();

                $n_m_id = 0;

                if($data['num']<1){
                    $this->error("箱格数量不能少于1");
                }

                $boxs = [];
                for($i=1; $i<=$data['num']; $i++){
                    $row = [];
                    $row['board_channel'] = ($maxs['board_'.$data['device_board'].'_max']??0)+$i;
                    $row['box_num'] = ($maxs['box_num_max']??0)+$i;
                    $row['box_type'] = $data['box_type'];
                    $row['s_id'] = $data['s_id'];
                    $row['d_id'] = $data['d_id'];
                    $row['device_board'] = $data['device_board'];
                    $boxs[] = $row;
                }
                $this->app->db->name("jcg_boxs")->insertAll($boxs);
                if($n_m_id>$device['box_count']){
                    $query->where("id", $device['id'])->update(['box_count'=>$n_m_id]);
                }
                $query->commit();
            }catch (\Exception $e){
                $query->rollback();
                $this->error("失败：".$e->getMessage());
            }
            $this->success("成功");
        }else{
            $this->assign("devices", $this->app->db->name('jcg_devices')->column("device_name", "id"));
        }
    }

    /**
     * 修改箱格状态
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function state()
    {
        $this->_save($this->table, $this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    /**
     * 删除箱格
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {
        $this->_delete($this->table);
    }

}